using System;
using OTE.Tasks.Commands.Question;
using SharpArch.Domain.Commands;
using SharpArch.NHibernate.Contracts.Repositories;

namespace OTE.Tasks.CommandHandlers.Question
{
    public class QuestionMetaDataUpdatedHandler : ICommandHandler<QuestionMetaDataUpdatedCommand>
    {
        private readonly INHibernateRepository<Domain.Category> _categoryRepository;
        private readonly INHibernateRepository<Domain.Question> _questionRepository;

        public QuestionMetaDataUpdatedHandler(INHibernateRepository<Domain.Category> categoryRepository, INHibernateRepository<Domain.Question> questionRepository)
        {
            _categoryRepository = categoryRepository;
            _questionRepository = questionRepository;
        }

        public ICommandResult Handle(QuestionMetaDataUpdatedCommand command)
        {
            var uow = _questionRepository.DbContext;

            var category = _categoryRepository.Get(command.CategoryId);

            Domain.Question question = null;

            question = _questionRepository.Get(command.Id);

            question.Category = category;
            question.Content = command.Content;
            question.ModifiedDate = DateTime.Now;
            question.ModifiedBy = command.ModifiedBy;

            var ques = _questionRepository.SaveOrUpdate(question);

            uow.CommitChanges();

            var result = ques == null
                ? new QuestionMetaDataUpdatedResult(false)
                : new QuestionMetaDataUpdatedResult(true) { Id = ques.Id };

            return result;
        }
    }
}